package test.streaming;

import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import test.MyFlatMapper;

/**
 * Stream流处理WordCount
 */
public class WordCount4 {

    public static void main(String[] args) throws Exception {
        //创建流处理执行环境（Flink上下文）
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //env.setParallelism(1);//并行度设置
        //用ParameterTool工具从程序启动参数中提取配置项
        ParameterTool parameterTool = ParameterTool.fromArgs(args);
        String host = parameterTool.get("host");
        Integer port = parameterTool.getInt("port");
        System.out.println("host: " + host + " port: " + port);
        //从Socket文本流读取数据
        DataStreamSource<String> inputDataStream = env.socketTextStream(host, port);
        //基于数据流进行转换计算
        SingleOutputStreamOperator<Tuple2<String, Integer>> resultStream = inputDataStream.flatMap(new MyFlatMapper())
                .keyBy(0)
                .sum(1);
        resultStream.print();
        //执行任务
        env.execute();
    }
}
